package com.tadpole.music.view.fragment.home;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.luck.picture.lib.permissions.RxPermissions;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.tadpole.music.R;
import com.tadpole.music.adapter.base.BaseAdapter;
import com.tadpole.music.adapter.base.HomePagerAdapter;
import com.tadpole.music.adapter.home.GaoKaoListAdapter;
import com.tadpole.music.adapter.home.NewInfoAdapter;
import com.tadpole.music.adapter.home.SchoolListAdapter;
import com.tadpole.music.adapter.home.RecommendedCoursesAdapter;
import com.tadpole.music.bean.PushBean;
import com.tadpole.music.bean.home.BannerBean;
import com.tadpole.music.bean.home.HomeNewInfoBean;
import com.tadpole.music.bean.me.MemberCenterBean;
import com.tadpole.music.config.Constant;
import com.tadpole.music.config.UrlConfig;
import com.tadpole.music.iView.home.BannerIView;
import com.tadpole.music.iView.home.HomeNewInfoIView;
import com.tadpole.music.iView.me.GaoKaoIView;
import com.tadpole.music.iView.me.MemberCenterIView;
import com.tadpole.music.presenter.home.BannerPresenter;
import com.tadpole.music.presenter.home.HomeNewInfoPresenter;
import com.tadpole.music.presenter.me.GaoKaoPresenter;
import com.tadpole.music.presenter.me.MemberCenterPresenter;
import com.tadpole.music.utils.Mutils;
import com.tadpole.music.utils.NoDoubleClickListener;
import com.tadpole.music.utils.SpUtil;
import com.tadpole.music.utils.ToastUtils;
import com.tadpole.music.view.activity.web.H5Activity;
import com.tadpole.music.view.activity.home.ClockInActivity;
import com.tadpole.music.view.activity.home.NewInfoListActivity;
import com.tadpole.music.view.activity.login.LoginActivity;
import com.tadpole.music.view.fragment.base.BaseFragment;
import com.tadpole.music.view.widget.vewipager.BannerIndicator;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;

/**
 * 首页
 * Created By 孙岩
 * on 2020/9/8
 */
public class HomeFragment extends BaseFragment implements BannerIView,  MemberCenterIView , HomeNewInfoIView , GaoKaoIView {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;
    //推荐课程recyclerview

    //学院列表
    private RecyclerView recyclerView;
    //推荐课程的adapter
    private RecommendedCoursesAdapter recommendedCoursesAdapter;

    //公告数据
    private List<String> noticeList = new ArrayList<>();

    //学院列表的adapter
    private SchoolListAdapter schoolListAdapter;

    //获取轮播图的presenter
    private BannerPresenter bannerPresenter;
    //轮播图
    private ViewPager viewpager;
    //指示器
    private BannerIndicator indicator;
    private ArrayList<Fragment> fragments;

    //获取公告presenter
//    private NoticePresenter noticePresenter;
    //我的院校
    private MemberCenterPresenter memberCenterPresenter;
    private List imagesList;
    private SmartRefreshLayout rlRefresh;
    //高考题库
    private RecyclerView rvGaokao;
    //高考adapter
    private GaoKaoListAdapter gaoKaoListAdapter;
    //最新资讯
    private LinearLayout llNewInfo;
    //最新资讯
    private RecyclerView ryNewInfo;
    //adapter
    private NewInfoAdapter newInfoAdapter;
    //更多
    private TextView tvMoreInfo;
    //获取最新资讯
    private HomeNewInfoPresenter homeNewInfoPresenter;
    //高考题库
    private GaoKaoPresenter gaoKaoPresenter;
    //打卡
    private ImageView tvClockIn;
    @Override
    public int getContentViewId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initAllMembersView(Bundle savedInstanceState) {
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected void initView(View mRootView) {
        recyclerView = mRootView.findViewById(R.id.recyclerView);
        viewpager = mRootView.findViewById(R.id.viewpager);
        indicator = mRootView.findViewById(R.id.indicator);
        rlRefresh = mRootView.findViewById(R.id.rl_refresh);
        ryNewInfo = mRootView.findViewById(R.id.ryNewInfo);
        tvMoreInfo = mRootView.findViewById(R.id.tvMoreInfo);
        llNewInfo = mRootView.findViewById(R.id.llNewInfo);
        tvClockIn = mRootView.findViewById(R.id.tvClockIn);
        rvGaokao = mRootView.findViewById(R.id.rvGaokao);
        //将头部状态栏置为透明
//        StatusBarUtil.setTranslucentForImageViewInFragment(getActivity(), 0, null);

        initListeners();
        bannerPresenter = new BannerPresenter();
        bannerPresenter.attachView(this);
        bannerPresenter.getBanner();

//        noticePresenter = new NoticePresenter();
//        noticePresenter.attachView(this);
//        noticePresenter.getNotice();
        //获取最新资讯
        homeNewInfoPresenter = new HomeNewInfoPresenter();
        homeNewInfoPresenter.attachView(this);
        homeNewInfoPresenter.getHomeNewInfo();
        //等级院校
        memberCenterPresenter = new MemberCenterPresenter();
        memberCenterPresenter.attachView(this);

        //高考题库
        gaoKaoPresenter = new GaoKaoPresenter();
        gaoKaoPresenter.attachView(this);
    }

    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    //初始化监听器
    private void initListeners(){
        //添加刷新监听器
        rlRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@io.reactivex.annotations.NonNull RefreshLayout refreshLayout) {
                bannerPresenter.getBanner();
//                noticePresenter.getNotice();
                memberCenterPresenter.getMemberCenter();
            }
        });

        //更多资讯
        tvMoreInfo.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if(Mutils.isNetworkAvailable()){
                    Intent intent = new Intent(getActivity(), NewInfoListActivity.class);
                    startActivity(intent);
                }else{
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });

        //打卡
        tvClockIn.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                if(Mutils.isNetworkAvailable()){
                    if(SpUtil.getInstance(getActivity()).getString(Constant.TOKEN,"").equals("")){
                        Intent intent = new Intent(getActivity(), LoginActivity.class);
                        startActivity(intent);
                    }else{
                        andPermission();
                    }

                }else{
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        memberCenterPresenter.getMemberCenter();
        gaoKaoPresenter.getMemberCenter();
    }

    //轮播图回调
    @Override
    public void showBanner(final List<BannerBean.DataBean> list) {
        if (list != null && list.size() != 0) {
            fragments = new ArrayList<>();

            list.add(0,new BannerBean.DataBean("",""));

            for(int i=0;i<list.size();i++){
                fragments.add(BannerFragment.newInstance(i+"",list.get(i).getThumb(),list.get(i).getLink_url()));
            }

            FragmentManager fm = getChildFragmentManager();
            HomePagerAdapter adapter = new HomePagerAdapter(fm, fragments);
            viewpager.setAdapter(adapter);
            indicator.setUpWidthViewPager(viewpager);

        }
    }


    @Override
    public void stopRefresh() {
        rlRefresh.finishRefresh();
        rlRefresh.finishLoadMore();
    }

//    //公告回调
//    @Override
//    public void showNoticeList(List<NoticeBean.DataBean> list) {
//        if (list != null && list.size() != 0) {
//            for (int i = 0; i < list.size(); i++) {
//                noticeList.add(list.get(i).getTitle());
//            }
//            tvText.startWithList(noticeList);
//        }
//    }

    @Override
    public void showMemberCenter(List<MemberCenterBean.DataBean> list) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getCollege_id() == 1) {
                list.get(i).getGoods().add(new MemberCenterBean.DataBean.GoodsBean(new MemberCenterBean.DataBean.GoodsBean.RankBean(list.get(0).getGoods().get(0).getId(), "在线套题")));
            }
        }

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        //创建适配器
        schoolListAdapter = new SchoolListAdapter(getActivity(), list);
        //给RecyclerView设置适配器
        recyclerView.setAdapter(schoolListAdapter);
        recyclerView.setNestedScrollingEnabled(false);
    }

    @Override
    public void showGaoKao(List<MemberCenterBean.DataBean> list) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        rvGaokao.setLayoutManager(layoutManager);
        //创建适配器
        gaoKaoListAdapter = new GaoKaoListAdapter(getActivity(), list);
        //给RecyclerView设置适配器
        rvGaokao.setAdapter(gaoKaoListAdapter);
        rvGaokao.setNestedScrollingEnabled(false);
    }

    @Override
    public void show401() {

    }

    @Override
    public void showHomeNewInfo(final List<HomeNewInfoBean.DataBean> list) {
        llNewInfo.setVisibility(View.VISIBLE);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        ryNewInfo.setLayoutManager(layoutManager);
        //创建适配器
        newInfoAdapter = new NewInfoAdapter(getActivity(),list);
        //给RecyclerView设置适配器
        ryNewInfo.setAdapter(newInfoAdapter);
        ryNewInfo.setNestedScrollingEnabled(false);

        newInfoAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                if(Mutils.isNetworkAvailable()){
                    PushBean pushBean = new PushBean();
                    pushBean.setUrl(UrlConfig.getNoticeInfo+list.get(position).getId());
                    pushBean.setTitle("公告详情");
                    Intent intent = new Intent(getActivity(), H5Activity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("params",pushBean);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }else{
                    ToastUtils.show("请检查您的网络设置");
                }
            }
        });
    }

    @Override
    public void show201() {
        llNewInfo.setVisibility(View.GONE);
    }

    //权限
    @SuppressLint("CheckResult")
    private void andPermission() {
        RxPermissions rxPermission = new RxPermissions(getActivity());
        rxPermission
                .request(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                ).subscribe(new Consumer<Boolean>() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                //请求权限成功
                if (aBoolean) {
                    Intent intent = new Intent(getActivity(), ClockInActivity.class);
                    startActivity(intent);
                } else {//失败
                    String msg = "请点击【去授权】打开相应权限！";
                    showAlert(msg);
                }
            }
        });
    }

    //授权
    public void showAlert(String msg) {
        new AlertDialog.Builder(getActivity()).setMessage(msg).
                setPositiveButton("去授权",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
                                intent.setData(uri);
                                startActivity(intent);
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).setCancelable(true).show();
    }
}
